﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Car_Rental;
using Entity;
using Entity.CommonEnums;
using System.Transactions;

namespace Data.Car_Rental
{
    /// <summary>
    /// 订车业务实现
    /// </summary>
    public class RentalRecordRepository : Car_RentalRepositoryBase, IRentalRecordRepository, IBackgroundRepository<RentalRecord>
    {
        #region IRentalRecordRepository 成员

        public Entity.VMessage RentalCar(RentalRecord entity)
        {
            VMessage vm = new VMessage();
            try
            {
                entity.Status = (int)RentalRecordStatus.Scheduled;
                this.Insert(entity);
                vm.IsComplete = true;
            }
            catch (Exception)
            {
                vm.IsComplete = false;
                throw;
            }
            return vm;
        }

        public Entity.VMessage CancelRentalCar(RentalRecord entity)
        {
            VMessage vm = new VMessage();
            try
            {
                entity.Status = (int)RentalRecordStatus.Cancel;
                this.Update(entity);
                vm.IsComplete = true;
            }
            catch (Exception)
            {
                vm.IsComplete = false;
                throw;
            }
            return vm;
        }

        /// <summary>
        /// 是否要排队
        /// 如果车的数量大于0，可以直接预定，否则需要排队
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool IsQueued(RentalRecord entity)
        {
            int ScheduledCount = this.GetModelForSite().Where(i => i.ProductID == entity.ProductID && (i.Status == (int)RentalRecordStatus.Rented || i.Status == (int)RentalRecordStatus.Scheduled)).Count(); //已经预定了某辆车的数量
            //return this.GetModelForSite().Where(i => i.ProductID == entity.ProductID && (i.Status == (int)RentalRecordStatus.Rented || i.Status == (int)RentalRecordStatus.Scheduled) && i.Product_Extend.ProductCount <= ScheduledCount).Count() > 0;

            return true;
        }

        public VMessage FinishRentalCar(RentalRecord entity)
        {
            VMessage vm = new VMessage();
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {

                    entity.Status = (int)RentalRecordStatus.Finished;
                    this.Update(entity);
                    new ProductRepository().UpdateProductCount(entity.ProductID, 1);//库存加1
                    #region 为第一名排队用户預定

                    RentalRecord queueEntity = this.GetModelForSite().Where(i => i.ProductID == entity.ProductID && i.Status == (int)RentalRecordStatus.Queuing).OrderByDescending(i => i.CreateDate).FirstOrDefault();
                    if (queueEntity != null)
                    {
                        this.Update(new RentalRecord { ID = queueEntity.ID, Status = (int)RentalRecordStatus.Scheduled });
                    }

                    #endregion
                    trans.Complete();
                    vm.IsComplete = true;
                }
                catch (Exception)
                {
                    vm.IsComplete = false;
                    throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            return vm;
        }

        public IQueryable<RentalRecord> GetModelForSite()
        {

            return this.GetModelForBackground().OrderByDescending(i => i.ID).Where(i => i.Status != (int)Status.Deleted);
        }

        public IQueryable<RentalRecord> GetModelForBackground()
        {
            var linq = from data in this.GetModel()
                       join data2 in new ProductRepository().GetModelForBackground() on data.ProductID equals data2.ProductID
                       select new RentalRecord_Ext
                       {
                           CreateDate = data.CreateDate,
                           EndTime = data.EndTime,
                           ID = data.ID,
                           Product_Extend = data2,
                           ProductID = data.ProductID,
                           ReturnCity = data.ReturnCity,
                           ReturnShop = data.ReturnShop,
                           StartTime = data.StartTime,
                           Status = data.Status,
                           UpateDate = data.UpateDate,
                           UserID = data.UserID,
                           OrderItemID = data.OrderItemID,

                       };
            return linq;

        }

        #endregion

        #region IRepository<RentalRecord> 成员

        public void Update(RentalRecord entity)
        {
            base.UpdateEntity(entity);
        }

        public void Update(IList<RentalRecord> list)
        {
            throw new NotImplementedException();
        }

        public void Insert(RentalRecord entity)
        {
            base.InsertEntity(entity);
        }

        public void Insert(IList<RentalRecord> list)
        {
            base.InsertEntity(list.Cast<Entity.EntityBase>().ToList());
        }

        public RentalRecord InsertGetIDENTITY(RentalRecord entity)
        {
            base.InsertEntity(entity);
            return Find(entity.ID);
        }

        public void Delete(RentalRecord entity)
        {
            throw new NotImplementedException();
        }

        public void Delete(IList<RentalRecord> list)
        {
            throw new NotImplementedException();
        }

        public IQueryable<RentalRecord> GetModel()
        {
            return base.GetEntities<RentalRecord>().Select(data => new RentalRecord_Ext
            {
                CreateDate = data.CreateDate,
                EndTime = data.EndTime,
                ID = data.ID,
                ProductID = data.ProductID,
                ReturnCity = data.ReturnCity,
                ReturnShop = data.ReturnShop,
                StartTime = data.StartTime,
                Status = data.Status,
                UpateDate = data.UpateDate,
                UserID = data.UserID,
                OrderItemID = data.OrderItemID,
            });
        }

        public RentalRecord Find(params object[] keyValues)
        {
            return base.Find<RentalRecord>(keyValues);
        }

        #endregion
    }
}
